<template>
<div>
  <v-row justify="center">
    <v-col cols="8">
        <v-data-table
            v-model="selected"
            :headers="headers"
            :items="items"
            :single-select="singleSelect"
            item-key="__id__"
            show-select
            class="elevation-1 mt-8"
        >
            <template v-slot:top>
            <v-toolbar flat class="blue lighten-4">
                <v-toolbar-title>{{ tableName }}</v-toolbar-title>
                <v-spacer></v-spacer>
                <v-btn 
                    outlined
                    @click="addItem"
                >
                    <v-icon left class="mdi mdi-plus"></v-icon>ADD
                </v-btn>
                <v-btn 
                    color="error"
                    outlined
                    @click="deleteItem"
                >
                    <v-icon left class="mdi mdi-delete"></v-icon>DEL
                </v-btn>
                <v-btn 
                    color="warning"
                    outlined
                    @click="alterItem"
                >
                    <v-icon left class="mdi mdi-delete"></v-icon>ALT
                </v-btn>
            </v-toolbar>
            </template>
        </v-data-table>

        <v-dialog v-model="dialog" persistent max-width="600px">
            <v-card>
                <v-card-title>
                <span class="headline">{{ dialogTitle }}</span>
                </v-card-title>
                <v-card-text>
                <v-container>
                    <!-- <v-row> -->
                    <!-- <v-form ref="form"> -->
                    <v-row cols="12" :key="i" v-for="(header, i) in headers">
                        <v-text-field
                            :label="header.text"
                            outlined
                            v-model="itemform[header.text]"
                        ></v-text-field>
                    </v-row>
                    <!-- </v-form> -->
                
                    <!-- </v-row> -->
                </v-container>
                </v-card-text>
                <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="blue darken-1" text @click="close">Close</v-btn>
                <v-btn color="blue darken-1" text @click="saveAddItem">Save</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-col>
  </v-row>
</div>
</template>

<script>

  export default {
    data () {
      return {
        dialogTitle: "ADD ITEM",
        tableName: '',
        singleSelect: false,
        selected: [],
        dialog: false,
        itemform: {TableName: ''},
        headers: [],
        items: [],
        // oldItem: null,
        // editItem: null,
        editIndex: -1
      }
    },
    created() {
        this.initialize()
    },
    methods: {
        initialize() {
            console.log(this.$route.params.name)
            this.tableName = this.$route.params.name
            this.itemform.TableName = this.tableName
            //todo: get table content from backend
            this.$axios.get('/api/get_table_content', {
                params:{            
                    TableName: this.tableName,   //参数，键值对，key值：value值
            }}).then(res=>{
                let data = res.data
                let headers = data.headers
                let items = data.items
                console.log(data)
                // console.log(headers)
                // console.log(items)
                for (let i = 0; i < headers.length; i++)
                {
                    this.headers.push({
                        text: headers[i],
                        value: headers[i]
                    })
                }
                

                for (let i = 0; i < items.length; i++)
                {
                    this.items.push(items[i])
                    this.items[i].__id__ = i;
                }
            })
        },
        addItem() {
            this.dialogTitle = "ADD ITEM"
            this.dialog = true
        },
        deleteItem() {
            // console.log(this.selected)
            if (this.selected.length == 0) 
                alert("Please select one item")
            else if(confirm('Are you sure you want to delete this item?')) {
                // console.log(this.selected)
                for (let i = 0; i < this.selected.length; i++)
                {
                    let index = this.items.indexOf(this.selected[i])
                    // console.log(index)
                    this.items.splice(index, 1)
                    
                    // this.selected[i].tableName = this.tableName
                    this.$delete(this.selected[i], '__id__')
                    var delItem = {tableName: this.tableName}
                    for (let j = 0; j < this.headers.length; j++)
                    {
                        delItem[this.headers[j].text] = this.selected[i][this.headers[j].text]
                        // console.log(delItem)
                    }
                    // delItem[this.headers[1].value] = "fuck"
                    // console.log(delItem)
                    this.$axios.post('/api/delete_from_table', delItem).then(res => {
                        // let index = this.items.indexOf(this.selected[i])
                        if (res.data.msg) alert(res.data.msg)
                        // else this.items.splice(index, 1)
                    })  
                }
                this.selected = []
            }
        },
        saveAddItem() {

            if (this.editIndex == -1) {
                console.log(this.itemform)
                //todo: post backend to add newitem before modifying at front, in order to do validation at backend
                this.$axios.post('/api/insert_into_table', this.itemform)
                    .then(res => {
                    console.log(res)
                    if (res.data.msg) alert(res.data.msg)
                    else {
                        this.itemform['__id__'] = this.items.length + 1
                        this.items.push(this.itemform)
                        this.itemform = {TableName: this.tableName}
                    }
                    this.dialog = false
                }) 
            }
            else {
                
                // console.log(this.itemform)
                // console.log(this.editIndex)
                // console.log(this.items[this.editIndex])
                let oldValue = Object.assign({}, this.items[this.editIndex])
                
                Object.assign(this.items[this.editIndex], this.itemform)
                // console.log("newValue", this.items[this.editIndex])
                let newValue = Object.assign({}, this.items[this.editIndex])
                this.$delete(oldValue, "__id__")
                this.$delete(newValue, "__id__")
                this.$delete(oldValue, "TableName")
                this.$delete(newValue, "TableName")
                console.log("oldValue", oldValue)
                console.log("newValue", newValue)
                this.$axios.post('/api/update_table', {tableName: this.tableName, oldValue: JSON.stringify(oldValue), newValue: JSON.stringify(newValue)})
                
                this.itemform = {TableName: this.tableName}
                this.selected = []
                this.editIndex = -1
                this.dialog = false
                
            }
        },
        alterItem() {
            this.dialogTitle = "ALTER ITEM"
            if (this.selected.length == 0)
                alert("Please select one item")
            else if (this.selected.length > 1)
                alert("Plese select One item at a time")
            else {
                this.dialog = true
                this.itemform = Object.assign({}, this.selected[0])
                // this.oldItem = Object.assign({}, this.selected[0])
                let index = this.items.indexOf(this.selected[0])
                this.editIndex = index
                // this.$delete(this.editItem, '__id__')
                // console.log(this.selected[0])
                // console.log(this.itemform)
                // console.log(this.editIndex)
            }
        },
        close() {
            this.dialog = false
            this.itemform = {TableName: this.tableName}
        }
    }
  }
</script>
